package com.tyhy.program.cbc.mobileapi.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class HttpCallUtil {
    private static final Logger log = LoggerFactory.getLogger(HttpCallUtil.class);

    private static RequestConfig requestConfigWithLongReadTime = null;
    private static RequestConfig requestConfigO2O = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
        requestConfigWithLongReadTime = RequestConfig.custom().setSocketTimeout(8000).setConnectTimeout(5000).build();
        requestConfigO2O = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(5000).build();
    }

    /**
     * 发起http请求
     *
     * @param HttpURL 请求链接
     * @param method  方法名：post、get
     * @param info    携带信息
     * @return
     */
    public static String CallHttp(String HttpURL, String method, String info) {
        HttpURLConnection httpurlconnection = null;
        String response = "";
        BufferedOutputStream out = null;
        BufferedReader in = null;
        InputStream is = null;
        try {
            // -------------------开始访问请求-------------------------------------------
            URL url = new URL(HttpURL);
            // 以post方式请求
            httpurlconnection = (HttpURLConnection) url.openConnection();
            httpurlconnection.setRequestProperty("content-type", "text/html; charset=utf-8");
            httpurlconnection.setDoOutput(true);
            httpurlconnection.setDoInput(true);
            httpurlconnection.setRequestMethod(method.toUpperCase());
            httpurlconnection.setConnectTimeout(5000);
            httpurlconnection.setReadTimeout(5000);
            if (info != null && !"".equals(info)) {
                info = URLEncoder.encode(info, "utf-8");
                /**
                 * 传输对象
                 */
                out = new BufferedOutputStream(httpurlconnection.getOutputStream());
                out.write(info.getBytes()); // 写入请求的字符串
                out.flush();
                out.close();

            }
            try {
                /**
                 * 当响应正常时，活的返回xml
                 */
                if (httpurlconnection.getResponseCode() == 200) {
                    is = httpurlconnection.getInputStream();
                    StringBuffer buffer = new StringBuffer();
                    try {
                        in = new BufferedReader(new InputStreamReader(is, "utf-8"));
                        String line = "";
                        while ((line = in.readLine()) != null) {
                            buffer.append(line);
                        }
                    } catch (IOException e) {
                        throw new Exception(e);
                    }
                    response = buffer.toString();
                }
            } catch (Exception e) {
                throw new Exception("获取HTTP服务返回对象出错！" + e);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpurlconnection != null) {
                httpurlconnection.disconnect();
            }
            try {
                if (in != null) {
                    in.close();
                    in = null;
                }
                if (is != null) {
                    is.close();
                    is = null;
                }
                if (out != null) {
                    out.close();
                    out = null;
                }
            } catch (IOException e) {
            }

        }
        return response.toString();
    }

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
    }

    /**
     * post请求传输json参数
     *
     * @param url  url地址
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        String str = "";
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (Exception e) {
        	log.error("post请求提交失败:url={},result={},error={}",url,str,e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * post请求传输String参数 例如：name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url      url地址
     * @param strParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        String str = "";
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("post请求提交失败:" + url, e);
                }
            }
        } catch (Exception e) {
        	log.error("post请求提交失败:url={},result={},error={}",url,str,e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        String strResult = "";
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            HttpEntity entity = response.getEntity();
            strResult = EntityUtils.toString(entity, "utf-8");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                log.error("get请求提交失败:" + url);
                log.error("get请求提交失败:strResult=" + strResult);
            }
        } catch (Exception e) {
        	log.error("get请求提交失败:url={},result={},error={}",url,strResult,e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }
    public static JSONArray httpGetArray(String url) {
        // get请求返回结果
        JSONArray jsonResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        String strResult = "";
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功，并得到响应
            HttpEntity entity = response.getEntity();
            strResult = EntityUtils.toString(entity, "utf-8");
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                jsonResult = JSONArray.parseArray(strResult);
            } else {
                log.error("get请求提交失败:" + url);
                log.error("get请求提交失败:strResult=" + strResult);
            }
        } catch (Exception e) {
        	log.error("get请求提交失败:url={},result={},error={}",url,strResult,e);

        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * put请求传输json参数
     *
     * @param url  url地址
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPut(String url, JSONObject jsonParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
//    	HttpPost httpPost = new HttpPost(url);
        HttpPut httpPut = new HttpPut(url);
        // 设置请求和传输超时时间
        httpPut.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPut.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPut);
            int statusCode = result.getStatusLine().getStatusCode();
            // 请求发送成功，并得到响应
            if (statusCode == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    log.error("put请求提交失败:{}",str);
                    log.error("put请求提交失败:" + url, e);
                }
            } else {
                log.info("put请求提交失败:statusCode=" + statusCode);
            }
        } catch (Exception e) {
            log.error("post请求提交失败:" + url, e);
        } finally {
            httpPut.releaseConnection();
        }
        return jsonResult;
    }
    /**
     * post请求传输json参数
     * <p>
     * 规划院接口使用,自定义了连接参数requestConfigWithLongReadTime
     * @param url  url地址
     * @param jsonParam 参数
     * @return
     * @throws Exception
     */
    public static String httpPost(String url,String contentType, JSONObject jsonParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String jsonResultStr = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfigWithLongReadTime);
//        httpPost.addHeader("", "");
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType(contentType);
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            jsonResultStr = EntityUtils.toString(result.getEntity(), "utf-8");
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                // 把json字符串转换成json对象
                return jsonResultStr;
            }else {
                //请求异常
                throw new RuntimeException("请求异常,未得到正常响应,msg="+jsonResultStr);
            }
        } catch (Exception e) {
            log.error("post请求提交失败:" + url, e);
        	log.error("get请求提交失败:url={},result={},error={}",url,jsonResultStr,e);

        } finally {
            httpPost.releaseConnection();
        }
        return jsonResultStr;
    }
    /**
     * post请求传输json参数
     * <p>
     * 规划院接口使用,自定义了连接参数requestConfigWithLongReadTime
     * @param url  url地址
     * @param jsonParam 参数
     * @return
     * @throws Exception
     */
    public static String httpPost(String url,String contentType, JSONObject jsonParam,Header header)  {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String resultStr = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfigWithLongReadTime);
        if(header !=null) {
            httpPost.addHeader(header);
        }
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType(contentType);
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            resultStr = EntityUtils.toString(result.getEntity(), "utf-8");
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                // 把json字符串转换成json对象
                return resultStr;
            }
        } catch (Exception e) {
            log.error("post请求提交失败:" + url, e);
        	log.error("get请求提交失败:url={},result={},error={}",url,resultStr,e);

        } finally {
            httpPost.releaseConnection();
        }
        return resultStr;
    }
    public static JSONObject httpPostO2O(String url, String strParam) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfigO2O);
        String str = "";
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功，并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                str = EntityUtils.toString(result.getEntity(), "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(str);
            }
        } catch (Exception e) {
        	log.error("post请求提交失败:url={},result={},error={}",url,str,e);

        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * put请求传输json参数
     *
     * @param url       url地址
     * @return
     */
    public static JSONObject httpPut(String url) {
        // post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        JSONObject jsonResult = new JSONObject();
//    	HttpPost httpPost = new HttpPost(url);
        HttpPut httpPut = new HttpPut(url);
        // 设置请求和传输超时时间
        httpPut.setConfig(requestConfig);
        try {
            CloseableHttpResponse result = httpClient.execute(httpPut);
            int statusCode = result.getStatusLine().getStatusCode();
            // 请求发送成功，并得到响应
            jsonResult.put("code", statusCode);
            if (statusCode == HttpStatus.SC_OK) {
                try {
                    jsonResult.put("msg", "提交成功");
                } catch (Exception e) {
                    jsonResult.put("msg", e.getMessage());
                }
            } else {
                jsonResult.put("msg", "提交失败");
                log.info("put请求提交失败:statusCode=" + statusCode);
            }
        } catch (Exception e) {
            jsonResult.put("msg", e.getMessage());
        	log.error("put请求提交失败:url={},result={},error={}",url,jsonResult,e);

        } finally {
            httpPut.releaseConnection();
        }
        return jsonResult;
    }


}
